package com.boot.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.common.message.BaseService;
import com.boot.common.message.RequestPageHead;
import com.boot.common.utils.ObjectUtils;
import com.boot.common.utils.StringUtils;
import com.boot.entity.user.UserEntity;
import com.boot.mapper.user.UserMapper;
import com.boot.redis.RedisUtil;
import com.boot.service.user.IUserServiceRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Cheng JiYe
 * @description:
 * @date 2020/10/3 20:22
 */
@Service
public class UserServiceImplRedis extends ServiceImpl<UserMapper, UserEntity> implements IUserServiceRedis {
    @Autowired
    private UserMapper modelMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<UserEntity> queryUserEntityList(RequestPageHead req) {
        BaseService.startPage(req);
        List<UserEntity> userEntities = (List<UserEntity>) redisUtil.get("queryUserEntityList-user" + JSON.toJSONString(req));
        if (CollectionUtils.isEmpty(userEntities)) {
            userEntities = modelMapper.queryUserEntityList();
            redisUtil.set("queryUserEntityList-user" + JSON.toJSONString(req), userEntities);
        }
        if (CollectionUtils.isEmpty(userEntities)) {
            userEntities = new ArrayList<>();
        }
        return userEntities;
    }

    @Override
    public UserEntity queryUserEntityById(UserEntity reqDetail) {
        UserEntity userEntity = (UserEntity) redisUtil.get("queryUserEntityById-user-redis" + JSON.toJSONString(reqDetail));
        if (ObjectUtils.isNull(userEntity)) {
            userEntity = modelMapper.selectById(reqDetail.getId());
            redisUtil.set("queryUserEntityById-user-redis" + JSON.toJSONString(reqDetail), userEntity);
        }

        if (StringUtils.isBlank(userEntity)) {
            return new UserEntity();
        }
        return userEntity;
    }
}
